<template>
  <!-- <a-spin :spinning="state.spinning"> -->
  <section class="flex w-full flex-col flex-1">
    <a-row
      :gutter="24"
      class="mb10 aic"
      style="margin-left: 0; margin-right: 0"
    >
      <div class="dib fs12" v-if="props.showSelection">
        已选择
        <span class="color-1989fa">{{ state.selectedRowKeys.length }}</span
        >条数据
        <a-button type="link" size="small" @click="onCancelSelect">
          取消选择
        </a-button>
      </div>
      <a-col flex="1">
        <slot name="btns"> </slot>
      </a-col>

      <cps-button
        size="small"
        class="mr10"
        plain
        icon="download"
        :loading="exportLoading"
        v-if="props.hasExport"
        @click="exportExcel"
        >导出</cps-button
      >
      <cps-button
        size="small"
        class="mr10"
        icon="refresh"
        v-if="props.hasRefresh"
        @click="refresh()"
        >刷新</cps-button
      >
      <cps-button
        v-if="props.hasReset"
        size="small"
        class="mr10"
        icon="refresh"
        @click="reset()"
      >
        重置
      </cps-button>
      <column-settings
        v-if="props.showSetting && !props.columns"
        class="show-setting"
        :buttonStyle="props.buttonStyle"
        v-model:value="state.menuListFields"
        :menuName="props.menuName"
        @change="refreshColumn"
      ></column-settings>
    </a-row>
    <div class="vxe-table-container flex-1" ref="tableContainerRef">
      <a-table
        v-dragWidth="{ columns: state.tableColumns, id: state.tableId }"
        bordered
        :uid="state.uid"
        :loading="state.spinning"
        size="small"
        ref="tableDom"
        :columns="state.tableColumns"
        :data-source="state.tableDatas"
        :pagination="false"
        @change="changeTable"
        class="myRemoteTable"
        :class="{
          tableEmpty: state.tableDatas.length === 0
        }"
        :scroll="{
          x: x || '100%',
          y: isCalcTableHeight || isAddBaseTableHeight ? state.yy : scrollY
        }"
        :row-selection="myRowSelection"
        :row-key="props.rowKey"
      >
        <!--   -->
        <!-- 自定义过滤器 -->
        <template
          v-for="(item, columnIndex) in state.tableColumns"
          :key="item?.slots?.filterDropdown"
          v-slot:[item?.slots?.filterDropdown]="{
            confirm,
            column,
            clearFilters
          }"
        >
          <!-- 批量搜索 -->
          <template v-if="item.isBatch">
            <div class="rm-popover pr p10">
              <h4 class="mb10">批量查询</h4>
              <a-input
                style="width: 100%"
                allowClear
                v-model:value="item.batchValue"
                placeholder="支持复制或输入关键词"
                @pressEnter="e => handlerBatchBlur(e, columnIndex)"
                @blur="e => handlerBatchBlur(e, columnIndex)"
              />
              <a-tag
                style="float: left"
                closable
                @close="handlerDelBatchItem(tIndex, columnIndex)"
                class="mb10"
                v-for="(t, tIndex) in item.batchTags"
                :key="t"
              >
                {{ t }}</a-tag
              >
            </div>
            <a-row class="action-wrap p10 df jcfe">
              <a-button
                size="small"
                class="mr10"
                @click="() => (item.isBatch = false)"
              >
                切换普通查询
              </a-button>
              <a-button
                size="small"
                class="mr10"
                type="primary"
                ghost
                @click="
                  () => {
                    item.batchTags = []
                    handleBatchSearch(confirm, column, true, columnIndex)
                  }
                "
              >
                重置
              </a-button>
              <a-button
                size="small"
                type="primary"
                @click="
                  () => {
                    handleBatchSearch(confirm, column, true)
                  }
                "
              >
                确定
              </a-button>
            </a-row>
          </template>
          <!-- 单个 搜索所 -->
          <template v-else>
            <div class="sort-wrap df jcsb p10">
              <div>
                <span
                  class="cp mr30"
                  :style="{
                    color: item.desc === 'asc' ? '#1989fa' : ''
                  }"
                  @click="handleSort('asc', columnIndex, confirm)"
                >
                  <SortAscendingOutlined />
                  <span class="fs12">升序</span>
                </span>
                <span
                  class="cp"
                  :style="{
                    color: item.desc === 'desc' ? '#1989fa' : ''
                  }"
                  @click="handleSort('desc', columnIndex, confirm)"
                >
                  <SortDescendingOutlined />
                  <span class="fs12">降序 </span>
                </span>
              </div>
              <div>
                <a-checkbox
                  v-if="item.needEmpty"
                  :key="item.isBlank"
                  :checked="item.isBlank"
                  @change="e => setBlank(e, columnIndex)"
                >
                  空
                </a-checkbox>
                <DiffOutlined
                  class="ml10"
                  :style="{
                    color: item.batchTags?.length > 0 ? '#1989fa' : ''
                  }"
                  v-if="item.isBatchQuery == 1"
                  @click="() => (item.isBatch = true)"
                  style="font-size: 20px"
                />
              </div>
            </div>
            <!-- 时间范围选择 -->
            <div v-if="item.model === 1" class="date-wrap mb10 pr10 pl10">
              <a-range-picker
                v-model:value="item.filterValue"
                style="width: 300px"
                format="YYYY-MM-DD"
                allowClear
                value-format="YYYY-MM-DD"
              />
            </div>
            <!-- 数字范围 model 7-->
            <div
              v-else-if="item.model === 7"
              class="number-wrap mb10 pr10 pl10 df aic jcc"
              style="width: 250px"
            >
              <a-input-number
                :min="0"
                placeholder="最小值"
                :precision="0"
                allowClear
                v-model:value="item.filterValue[0]"
                class="mr10 f1"
              />
              ~
              <a-input-number
                :min="item.filterValue[0] || 0"
                :precision="0"
                allowClear
                placeholder="最大值"
                v-model:value="item.filterValue[1]"
                class="ml10 f1"
              />
            </div>
            <div
              v-else
              class="search-wrap pr10 pl10"
              style="border-bottom: 1px solid #eaeaea; max-width: 300px"
            >
              <!-- 远程搜索 -->
              <a-input-search
                v-if="item.model === 2"
                :placeholder="`搜索 ${column.customeTitle}`"
                :loading="state.loading"
                v-model:value="item.params.queryStr"
                @change="e => remoteSearch(e, columnIndex)"
              />
              <a-input
                v-else
                v-model:value="item.searchValue"
                :placeholder="`搜索 ${column.customeTitle}`"
                @change="e => inputSearch(e, columnIndex)"
                @pressEnter="() => handleSearch(confirm, column)"
              />
              <div class="checkbox-wrap">
                <a-spin :spinning="state.loading">
                  <a-checkbox
                    :key="item.checkAll"
                    :checked="item.checkAll"
                    :indeterminate="item.indeterminate"
                    @change="e => onCheckAllChange(e, columnIndex)"
                  >
                    全选
                  </a-checkbox>
                  <span v-if="item.plainOptions"
                    >({{ item.filterValue ? item.filterValue.length : 0 }}/
                    {{ item.plainOptions && item.plainOptions.length }})</span
                  >
                  <a-divider
                    dashed
                    style="margin-top: 10px; margin-bottom: 10px"
                  />
                  <a-checkbox-group
                    v-model:value="item.filterValue"
                    @change="values => onChange(values, columnIndex)"
                  >
                    <div v-for="c in item.plainOptions" :key="c.value">
                      <a-checkbox :value="c.key" :label="c.key">
                        {{ c.value || '空' }}
                      </a-checkbox>
                    </div>
                  </a-checkbox-group>
                </a-spin>
              </div>
            </div>

            <div class="action-wrap p10 df jcfe">
              <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="() => handleSearch(confirm, column)"
              >
                <template #icon>
                  <SearchOutlined />
                </template>
                搜索
              </a-button>
              <a-button
                size="small"
                style="width: 90px"
                @click="() => handleReset(confirm, columnIndex, clearFilters)"
              >
                重置
              </a-button>
            </div>
          </template>
        </template>
        <template
          v-for="item in state.tableColumns"
          :key="item?.slots && item.slots.title"
          v-slot:[item?.slots&&item.slots.title]
        >
          <slot
            :name="item?.slots ? item.slots.title : ''"
            v-bind="{ text: item.customeTitle, record: item }"
          >
            <span v-if="item.notes">
              {{ item.customeTitle }}
              <a-tooltip>
                <template #title>{{ item.notes }}</template>
                <ExclamationCircleOutlined />
              </a-tooltip>
            </span>
            <span v-else>
              {{ item.customeTitle }}
            </span>
          </slot>
        </template>
        <!-- customerRender -->
        <template
          v-for="item in state.tableColumns"
          :key="item?.slots && item.slots.customRender"
          v-slot:[item?.slots&&item.slots.customRender]="{
            text,
            record,
            index
          }"
        >
          <slot
            :name="item?.slots ? item.slots.customRender : ''"
            v-bind="{ text, record, index, childrenList: item.childrenList }"
          >
            <span v-if="!item.childrenList || item.childrenList.length === 0">
              {{ record[item.dataIndex] }}
            </span>
            <div v-for="c in item.childrenList" v-else :key="c.requestStr">
              {{ c.columnName }}：{{ record[c.requestStr] || '-' }}
            </div>
          </slot>
        </template>
        <template #footer v-if="hasFooter">
          <slot name="footer"></slot>
        </template>
      </a-table>
    </div>
    <div
      ref="pagination"
      v-if="props.hasPaginate"
      class="df jcsb h-40px items-center px-10px"
      style="padding-bottom: 0"
    >
      <div class="o06">
        {{
          `共 ${state.total || 0}条数据，第${state.pageNum}/${Math.ceil(
            (state.total || 0) / state.pageSize
          )}页`
        }}
      </div>
      <div>
        <a-pagination
          size="small"
          :page-size="state.pageSize"
          v-model:current="state.pageNum"
          :total="state.total"
          @change="changePage"
          @showSizeChange="changePage"
          :pageSizeOptions="['20', '50', '100', '150', '200', '500']"
          show-size-changer
          show-quick-jumper
        />
      </div>
    </div>
  </section>
  <!-- </a-spin> -->
</template>
<script setup>
import { reactive, watch, onMounted, computed, ref, nextTick } from 'vue'
import ColumnSettings from './ColumnSettings.vue'
import { config_list_menu_field_post_ } from 'server/apis/4802.js'
import { debounce, cloneDeep } from 'lodash-es'
import { observeDomResize } from 'utils'
import {
  SearchOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined,
  DiffOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import {
  executeServer,
  getConfigColumn,
  executeSearch,
  useColumnWidth,
  useInitState
} from './remoteTable.js'
const props = defineProps({
  value: {
    type: Array
  },
  // 获取列接口的菜单名称
  menuName: {
    type: String
  },
  tableId: {
    type: String
  },
  // 是否支持多选
  showSelection: {
    type: Boolean,
    default: true
  },
  interfaceURL: {
    type: String,
    default: ''
  },
  // 是否显示列设置
  showSetting: {
    type: Boolean,
    default: false
  },
  hasExport: {
    type: Boolean,
    default: false
  },
  hasReset: {
    type: Boolean,
    default: true
  },
  hasRefresh: {
    type: Boolean,
    default: true
  },
  // 表格是否显示分页
  hasPaginate: {
    type: Boolean,
    default: true
  },
  // 是否显示操作项目
  hasAction: {
    type: Boolean,
    default: false
  },
  //是否显示底部
  hasFooter: {
    type: Boolean,
    default: false
  },
  // 是否立即查询数据，若为false，则手动调refresh或reset
  immediate: {
    type: Boolean,
    default: true
  },
  // 列设置的按钮样式
  buttonStyle: {
    type: Object,
    default: () => {
      return {}
    }
  },
  // 列宽设置
  columnWidth: {
    type: Object,
    default: () => {
      return {}
    }
  },
  columnFixed: {
    type: Object,
    default: () => {
      return {}
    }
  },
  y: {
    type: [String, Number],
    default: 770
  },
  sy: {
    type: [String, Number],
    default: 590
  },
  x: {
    type: [String, Number],
    default: 0
  },
  // 拉取table数据的接口参数
  apiParams: {
    type: Object,
    default: () => {
      return {}
    }
  },
  // 场景： 网址带搜索条件，打开网站后默认进行过滤搜索
  queryParams: {
    type: Object,
    default: () => {
      return {}
    }
  },
  columns: {
    type: Array,
    default: null
  },
  rowKey: {
    type: Function,
    default: r => r.id
  },
  // 使用场景，以某个字段的值为条件，查询满足这个条件下的所有筛选项
  // 列设置的参数
  queryFields: {
    type: Array,
    default: () => {
      return []
    }
  },
  pageSize: {
    type: Number,
    default: 50
  },
  rowType: {
    type: String,
    default: 'checkbox'
  },
  selectRowKeys: {
    type: Array,
    default: () => {
      return null
    }
  },
  // 发送请求前function
  beforeReqLoad: {
    type: Function,
    default: null
  },
  // 接口响应后function
  afterRespLoad: {
    type: Function,
    default: null
  },
  getCheckboxProps: {
    type: Function,
    default: null
  },
  canChangeColumnWidth: {
    type: Boolean,
    default: true
  },
  method: {
    type: String,
    default: 'post'
  },
  // 表格高度是否自动计算
  isCalcTableHeight: {
    type: Boolean,
    default: false
  },
  // 是否给表格增加默认值
  isAddBaseTableHeight: {
    type: Boolean,
    default: false
  },
  filterStorage: {
    type: Boolean,
    default: false
  },
  // 是否监听apiParams变了后查询接口
  isWatchApiParams: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(['update:value', 'change', 'select'])

const tableDom = ref(null)
const tableContainerRef = ref(null)
const exportLoading = ref(false)

const state = reactive({
  method: props.method,
  beforeReqLoad: props.beforeReqLoad,
  interfaceURL: props.interfaceURL,
  hasPaginate: props.hasPaginate,
  columnWidth: props.columnWidth || {},
  tableId: props.tableId || props.menuName || 'remoteTable',
  tableDatas: [],
  options: [],
  tableColumns: [],
  query: {
    sortList: [],
    ...props.queryParams
  },
  uid: 0,
  loading: false,
  pageNum: 1,
  pageSize: props.pageSize,
  spinning: false,
  total: 0,
  localApiParams: props.apiParams
    ? JSON.parse(JSON.stringify(props.apiParams))
    : {},
  menuListFields: [],
  selectedRowKeys: props.selectRowKeys || [],
  selectedRows: [],
  currentPageRowKeys: {},
  pageRows: {},
  mql: window.matchMedia('(max-width: 1400px)'),
  yy: true
})
watch(
  () => state.tableColumns,
  val => {
    console.log(val, 'tableColumns')
  },
  {
    immediate: true,
    deep: true
  }
)
/**
 * 创建列
 */
state.createColumns = datas => {
  state.tableColumns = cloneDeep(datas)
  state.tableColumns.forEach(element => {
    element.filtered = !!element.filterValue?.length
    element.width = useColumnWidth(element, state)
    if (element.slots?.filterDropdown) {
      element.onFilterDropdownVisibleChange = visible => {
        onFilterDropdownVisibleChange(visible, element)
      }
    }
  })
}

// 列筛选
const onFilterDropdownVisibleChange = (visible, item) => {
  if (visible) {
    nextTick(() => {
      item.filtered = true
      item.isBatch = false
    })

    if (props.queryFields?.length) {
      item.params.queryFields = props.queryFields
    }
    if (![1].includes(item.model)) {
      getConfigColumn(item, state)
    }
  }
  nextTick(() => {
    item.filtered =
      !!item.filterValue.length ||
      !!item.batchTags?.length ||
      item.desc ||
      item.isBlank
  })
}
// 全选
const onCheckAllChange = (e, index) => {
  const item = state.tableColumns[index]
  item.checkAll = e.target.checked
  item.indeterminate = false
  item.filterValue = e.target.checked ? item.plainOptions.map(e => e.key) : []
  state.tableColumns[index] = item
}
// 设置筛选空数据
const setBlank = (e, index) => {
  const item = state.tableColumns[index]
  item.isBlank = e.target.checked
  state.tableColumns[index] = item
}
// 输入框本地模糊匹配搜索
const inputSearch = debounce(function (e, index) {
  if (e.target.value) {
    state.tableColumns[index].plainOptions = state.options.filter(
      _ =>
        _.value &&
        _.value.toLowerCase().includes(e.target.value.trim().toLowerCase())
    )
  } else {
    state.tableColumns[index].plainOptions = state.options
  }
}, 300)
// 远程搜索
const remoteSearch = debounce(function (e, index) {
  state.loading = true
  const item = state.tableColumns[index]
  item.params.queryStr = e.target.value ? e.target.value.trim() : ''
  getConfigColumn(item, state)
}, 300)

const onChange = (checkedList, index) => {
  const item = state.tableColumns[index]
  state.tableColumns[index].checkAll =
    checkedList.length === item.plainOptions.length
  state.tableColumns[index].indeterminate =
    !!checkedList.length && checkedList.length < item.plainOptions.length
}
// 点击搜索
const handleSearch = (comfirm, column) => {
  state.pageNum = 1
  column.isBatch = false
  column.filtered = !!column.filterValue.length
  comfirm()
  executeSearch(state, props)
}
// 列筛选重置
const handleReset = (comfirm, index) => {
  state.pageNum = 1
  resetColumnFilter(index)
  comfirm()
  executeSearch(state, props)
}
// 排序
const handleSort = (sort, index, comfirm) => {
  state.tableColumns[index].desc = sort
  comfirm && comfirm()
  executeSearch(state, props)
}
const changeTable = (pag, filters, sorter) => {
  const obj = {
    ascend: 'asc',
    descend: 'desc'
  }
  if (sorter) {
    handleSort(
      sorter.order ? obj[sorter.order] : '',
      state.tableColumns.findIndex(item => item.key === sorter.columnKey)
    )
  }
  console.log(pag, filters, sorter)
}
// 批量查询输入失去焦点
const handlerBatchBlur = (e, index) => {
  const batchTags = state.tableColumns[index].batchTags
  if (!batchTags) {
    state.tableColumns[index].batchTags = []
  }
  const valueStr = e.target.value.replaceAll(/\t|\n|\s+/g, ' ')
  const values = valueStr.split(' ').filter(item => {
    return item.trim() !== ''
  })
  state.tableColumns[index].batchTags = [
    ...new Set(state.tableColumns[index].batchTags.concat(values))
  ]
  state.tableColumns[index].batchValue = null
}
// 删除输入记录
const handlerDelBatchItem = (index, columnIndex) => {
  state.tableColumns[columnIndex].batchTags.splice(index, 1)
}
const handleBatchSearch = (comfirm, column, isBatch, index) => {
  state.pageNum = 1
  column.filtered = !!column.batchTags?.length
  if (index >= 0) {
    resetColumnFilter(index)
  }

  column.isBatch = isBatch
  comfirm()
  executeSearch(state, props)
}
// 分页
const changePage = (page, size) => {
  state.pageNum = page
  state.pageSize = size
  executeServer(state, props)
}
// 重置全部清空
const reset = apiParams => {
  if (
    apiParams &&
    Object.prototype.toString.call(apiParams) === '[object Object]'
  ) {
    state.localApiParams = apiParams
  }
  state.pageNum = 1
  state.pageSize = props.pageSize
  state.query = { sortList: [] }
  clearFilter()
  onCancelSelect()
  state.interfaceURL && executeServer(state, props)
  emits('reset')
}
// 重置列条件信息
const resetColumnFilter = index => {
  state.tableColumns[index].filterValue = []
  state.tableColumns[index].indeterminate = false
  state.tableColumns[index].checkAll = false
  state.tableColumns[index].desc = ''
  state.tableColumns[index].filtered = false
  state.tableColumns[index].searchValue = null
  state.tableColumns[index].isBatch = false
  state.tableColumns[index].isBlank = false
  if (state.tableColumns[index].params) {
    state.tableColumns[index].params.queryStr = ''
  }
  state.tableColumns[index].batchTags = []
}
const updateColumnField = index => {
  const key = state.tableColumns[index].key
  if (state.query[key]) {
    state.tableColumns[index].filtered = true
    state.tableColumns[index].filterValue = state.query[key]
    state.uid++
  }
}
const clearFilter = () => {
  state.uid++
  state.tableColumns.forEach((item, index) => {
    resetColumnFilter(index)
  })
}
// 取消复选框
const onCancelSelect = () => {
  state.selectedRowKeys = []
  state.currentPageRowKeys = {}
  emits('change', state.selectedRowKeys, [], state.tableDatas)
}
const onSelectChange = (selectedRowKeys, selectedRows) => {
  // this.$set(this.currentPageRowKeys, this.pageNum, selectedRowKeys)
  if (props.rowType === 'radio') {
    state.currentPageRowKeys = {
      [state.pageNum]: selectedRowKeys
    }
    state.pageRows = { [state.pageNum]: selectedRows }
    return
  }
  state.currentPageRowKeys[state.pageNum] = selectedRowKeys
  state.pageRows[state.pageNum] = selectedRows
}
const onSelect = (record, selected) => {
  const index = state.tableDatas.findIndex(item => {
    return item.id === record.id
  })
  state.tableDatas[index].selected = selected

  emits('select', record, selected)
}

// 刷新只刷新当前页，保留用户操作的记录
const refresh = apiParams => {
  if (
    apiParams &&
    Object.prototype.toString.call(apiParams) === '[object Object]'
  ) {
    state.localApiParams = apiParams
  }
  state.interfaceURL && executeSearch(state, props)
  onCancelSelect()
  emits('refresh')
}
const refreshColumn = () => {
  console.log(props, 'props')
  state.tableColumns = []
  config_list_menu_field_post_(props, state)
  executeSearch(state, props)
}

const getPathName = () => {
  const query = window.location.href.split('?')[1]
  const search = query ? `?${query}` : ''
  const url = window.location.hash
    ? window.location.hash.slice(2)
    : window.location.hash.slice(1)
  return url.replace(search, '').replace(/\//g, '_')
}
/**
 * 本地保存用户拖拽的列宽
 */
const setColumnWidth = () => {
  const pathname = getPathName()
  const columnWidths = localStorage.getItem('dragWidth')
  if (columnWidths) {
    state.columnWidth = JSON.parse(columnWidths)[pathname]
      ? JSON.parse(columnWidths)[pathname][state.tableId]
      : props.columnWidth
  }
}
const setQueryParams = val => {
  Object.assign(state.query, val)
  state.tableColumns.forEach((item, index) => {
    updateColumnField(index)
  })
}
// 导出
const exportExcel = () => {
  exportLoading.value = true
  emits(
    'export',
    {
      ...props.apiParams,
      ...state.query
    },
    {
      pageNum: state.pageNum,
      pageSize: state.pageSize
    }
  )
  setTimeout(() => {
    exportLoading.value = false
  }, 1000)
}
// 获取接口所有参数
const queryAllParams = () => {
  return {
    ...props.apiParams,
    ...state.query,
    pageNum: state.pageNum,
    pageSize: state.pageSize
  }
}

const scrollY = computed(() => {
  const mql = window.matchMedia('(max-width: 1400px)')
  if (mql.matches) {
    return (props.sy || state.sy || 590) - (props.hasFooter ? 50 : 0)
  }
  return (props.y || state.y) - (props.hasFooter ? 50 : 0)
})
const myRowSelection = computed(() => {
  const { pageNum } = state
  const { rowType } = props
  if (props.showSelection) {
    const selectedRowKeys =
      state.currentPageRowKeys[pageNum] || props.selectRowKeys
    return {
      fixed: 'left',
      selectedRowKeys,
      type: rowType,
      onChange: onSelectChange,
      onSelect: onSelect,
      getCheckboxProps: props.getCheckboxProps
    }
  }
  return null
})

// 双向绑定当前页的表格数据
watch(
  () => state.tableDatas,
  val => {
    emits('update:value', val)
  },
  {
    deep: true
  }
)
watch(
  () => props.value,
  val => {
    state.tableDatas = val || []
  },
  {
    immediate: true,
    deep: true
  }
)
watch(
  () => props.columns,
  val => {
    val && state.createColumns(val)
  },
  {
    immediate: true,
    deep: true
  }
)
watch(
  () => props.apiParams,
  val => {
    if (
      JSON.stringify(val) !== JSON.stringify(state.localApiParams) &&
      props.isWatchApiParams
    ) {
      state.localApiParams = JSON.parse(JSON.stringify(val))
      changePage(1, state.pageSize)
    }
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => state.currentPageRowKeys,
  val => {
    state.selectedRowKeys = []
    state.selectedRows = []
    const keys = Object.keys(val)
    if (keys.length) {
      keys.map(item => {
        state.selectedRowKeys = [...state.selectedRowKeys, ...val[item]]
        state.selectedRows = [...state.selectedRows, ...state.pageRows[item]]
        emits(
          'change',
          state.selectedRowKeys,
          state.selectedRows,
          state.tableDatas
        )
      })
    } else {
      emits('change', [], [])
    }
  },
  {
    deep: true
  }
)
/**
 * 计算表格的高度
 */
const observeTableHeight = () => {
  if (props.isAddBaseTableHeight) {
    state.yy = tableContainerRef.value.clientHeight - 40 + 'px'
  } else {
    const boxHeight = document.body.offsetHeight
    const node = tableDom.value?.$el

    node &&
      observeDomResize(node, () => {
        const { top } = node.getBoundingClientRect()
        state.yy = Math.max(boxHeight - top - 130, scrollY.value)
      })
  }
}
onMounted(() => {
  useInitState(props, state)
  if (props.canChangeColumnWidth) {
    setColumnWidth()
  }
  if (!props.columns?.length) {
    config_list_menu_field_post_(props, state)
  }
  props.immediate && executeServer(state, props)

  nextTick(() => {
    observeTableHeight()
  })
  window.onresize = () => {
    observeTableHeight()
  }
})

defineExpose({
  queryTableData: () => {
    executeServer(state, props)
  },
  changePage,
  onCancelSelect,
  menuListFields: state.menuListFields,
  // updateTableColumn,
  getTableColumns: () => {
    return state.menuListFields
  },
  reset,
  refresh,
  setQueryParams,
  refreshColumn,
  queryAllParams
})
</script>

<style lang="scss" scoped>
.rm-popover {
  width: 300px;
  max-height: 400px;
  min-height: 200px;
  overflow-y: auto;
}
</style>
<style>
.search-wrap .checkbox-wrap {
  margin-top: 6px;
}
.search-wrap .ant-checkbox-group {
  min-height: 40px;
  max-height: 200px;
  overflow-y: scroll;
  width: 220px;
}

.search-wrap .ant-checkbox-group .ant-checkbox-wrapper {
  word-break: break-all;
  font-size: 12px;
  display: flex;
}

.search-wrap .ant-checkbox-group .ant-checkbox {
  margin-top: 3px;
  height: 16px;
}

.ant-table-footer {
  padding: 8px 4px;
}

.tableEmpty .ant-table-empty .ant-table-tbody {
  height: 208px;
}

.tableEmpty .ant-table-empty .ant-table-placeholder {
  position: absolute;
  width: 100%;
  top: 51px;
  z-index: 5;
}
</style>
